
import os
import pandas as pd

from PyQt5.QtWidgets import QDialog

from utils.define import UNSHOW_INDEX, UNSHOW_DEFAULT, FILE_DATA_PATH
from utils.tools import showMessageBox
from ui.dynamicMultiSelectDialog import DynamicMultiSelectDialog

def check_wrong_price(dataManager):
        out_data = pd.DataFrame(columns=['姓名', '日期', '名称及规格', '单价', '参考价格', '参考数量'])
        for customer in dataManager.nameList:
            data = pd.read_csv(dataManager.fileDict[customer], encoding="utf-8", dtype={
                "日期": str,
                "名称及规格": str,
                "单位": str,
                "数量": str,
                "单价": str,
                "备注": str,
                "金额": str,
                "deleted": bool
            })
            '''
                repeat_data = {
                    名称: {
                        价格1: 数量,
                        价格2: 数量,
                        ...
                    }
                }
            '''
            repeat_data = {}
            # 统计不一致数据次数
            for row in data.itertuples():
                if row.deleted == True:
                    continue

                name, value = row.名称及规格, row.单价
                if not repeat_data.get(name):
                    repeat_data[name] = {}
                if not repeat_data.get(name).get(value):
                    repeat_data[name][value] = 0
                repeat_data[name][value] += 1

            deleted_keys = []
            for key, values in repeat_data.items():
                if len(values) == 1:
                    deleted_keys.append(key)
            for key in deleted_keys:
                repeat_data.pop(key)

            # 筛选出来的获取各自日期并构造表格
            for row in data.itertuples():
                if row.deleted == True:
                    continue

                name, value, date = row.名称及规格, row.单价, row.日期
                if name in repeat_data.keys():
                    repeat_values = repeat_data.get(name)
                    if repeat_values.get(value) and repeat_values.get(value) <= 10:

                        max_k, max_v = 0, 0
                        for comp_k, comp_v in repeat_values.items():
                            if comp_v > max_v:
                                max_k, max_v = comp_k, comp_v

                        new_data = {'姓名': customer, '日期': date, '名称及规格': name, '单价': value,
                                    '参考价格': max_k, '参考数量': max_v}
                        out_data = pd.concat([out_data, pd.DataFrame([new_data])], ignore_index=True)
        if len(out_data) > 0:
            showMessageBox("检测到价格不一致，已输出到csv文件夹")
            out_data.to_csv(os.path.join(FILE_DATA_PATH, "价格不一致.csv"), encoding="utf-8", index=False)



'''
    统计所有客户的名称及规格和单价，弹窗选择正确价格，返回正确价格列表

    return: {
        "normal": { 名称: [正确价格1, 正确价格2, ...], ...},
        "特殊客户1": { 名称: [正确价格1, 正确价格2, ...], ...},
        ...
'''
def make_n2uDict(nameList, fileDict, specNames):
    repeat_data = {}
    spec_repeat_data = {name: {} for name in specNames}
    # 统计不一致数据次数
    for customer in nameList:
        data = pd.read_csv(fileDict[customer], encoding="utf-8", dtype={
            "日期": str,
            "名称及规格": str,
            "单位": str,
            "数量": str,
            "单价": str,
            "备注": str,
            "金额": str,
            "deleted": bool
        })
        for row in data.itertuples():
            if row.deleted == True:
                continue
            # 根据客户名选择不同字典存储
            curDict = None
            if customer in specNames:
                curDict = spec_repeat_data[customer]
            else:
                curDict = repeat_data

            name, value = row.名称及规格, row.单价
            if not curDict.get(name):
                curDict[name] = {}
            if not curDict.get(name).get(value):
                curDict[name][value] = 0
            curDict[name][value] += 1

    n2U_dict = {}
    spec_n2U_dict = {name: {} for name in specNames}
    # 过滤掉只出现一次暨价格正常的数据并存入结果字典
    def filter_normal_price(repeat_dict, result_dict):
        deleted_keys = []
        for key, values in repeat_dict.items():
            if len(values) == 1:
                deleted_keys.append(key)
        for key in deleted_keys:
            result_dict[key] = [list(repeat_dict[key].keys())[0]]
            repeat_dict.pop(key)

    filter_normal_price(repeat_data, n2U_dict)
    for name in specNames:
        filter_normal_price(spec_repeat_data[name], spec_n2U_dict[name])

    # 弹出对话框选择价格
    def choose_price(repeat_dict, result_dict, specName=None):
        spec = specName is not None and f"客户 {specName} \n\n" or ""
        for key, values in repeat_dict.items():
            values_list = [f"{k} (数量: {v})" for k, v in sorted(values.items(), key=lambda item: item[1], reverse=True)]
            dialog = DynamicMultiSelectDialog("选择价格", f"{spec}名称及规格: {key}\n请选择一个价格作为标准价格:", values_list)

            chosenValues = None
            if dialog.exec_() == QDialog.Accepted:
                selected_values = dialog.get_selection()
                chosenValues = [selected_value.split(" ")[0] for selected_value in selected_values]
                result_dict[key] = chosenValues.copy()
            else:
                # 用户取消选择，默认选择出现次数最多的价格
                max_k, max_v = 0, 0
                for comp_k, comp_v in values.items():
                    if comp_v > max_v:
                        max_k, max_v = comp_k, comp_v
                result_dict[key] = [max_k]
                chosenValues = [max_k]

            for chosenValue in chosenValues:
                values.pop(chosenValue)

    choose_price(repeat_data, n2U_dict)
    for name in specNames:
        choose_price(spec_repeat_data[name], spec_n2U_dict[name], specName=name)

    out_data = pd.DataFrame(columns=['姓名', '日期', '名称及规格', '单价', '正确价格'])
    # 再次遍历数据，找出不符合标准价格的数据位置, 方便用户修改
    for customer in nameList:
        data = pd.read_csv(fileDict[customer], encoding="utf-8", dtype={
            "日期": str,
            "名称及规格": str,
            "单位": str,
            "数量": str,
            "单价": str,
            "备注": str,
            "金额": str,
            "deleted": bool
        })
        for row in data.itertuples():
            if row.deleted == True:
                continue
            # 根据客户名选择不同字典存储
            curDict = None
            if customer in specNames:
                curDict = spec_repeat_data[customer]
            else:
                curDict = repeat_data

            name, value = row.名称及规格, row.单价
            if curDict.get(name) and curDict.get(name).get(value):
                curDict[name][value] -= 1
                if curDict[name][value] <= 0:
                    curDict[name].pop(value)
                if len(curDict[name]) == 0:
                    curDict.pop(name)
                new_data = {'姓名': customer, '日期': row.日期, '名称及规格': name, '单价': value,
                            '正确价格': n2U_dict.get(name) if customer not in specNames else spec_n2U_dict[customer].get(name)}
                out_data = pd.concat([out_data, pd.DataFrame([new_data])], ignore_index=True)

    if len(out_data) > 0:
        showMessageBox("检测到价格不一致，已输出到csv文件夹")
        out_data.to_csv(os.path.join(FILE_DATA_PATH, "价格错误列表.csv"), encoding="utf-8", index=False)

    spec_n2U_dict["normal"] = n2U_dict

    return spec_n2U_dict